/*
 * main.c
 *
 *  Created on: 2011-8-1
 *      Author: lius
 */
#include "header.h"



connect_server(int sock, char *ser_addr, unsigned short d_port)
{
	int ret = 0;
	struct sockaddr_in clientaddr;

	clientaddr.sin_family = AF_INET;
	clientaddr.sin_port = htons(d_port);
	inet_aton(ser_addr, &clientaddr.sin_addr);

	ret = connect(sock, &clientaddr, sizeof(clientaddr));
	printf("ret = %d,%s\n", ret,strerror(errno));
	return ret;
}

create_tcp_sock(char *bind_addr, char *dest_addr, unsigned short s_port)
{
	int ret = 0;
	int sock = socket(AF_INET, SOCK_STREAM, 0);
	if(sock < 0)
	{
		printf("[%d]%s\n", errno, strerror(errno));
		return sock;
	}

	struct ifreq if_ethx;
	strncpy(if_ethx.ifr_name, bind_addr, IFNAMSIZ);

	if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE,
	(char *) &if_ethx, sizeof(if_ethx)) < 0)
	{
		printf("[%d]%s\n", errno, strerror(errno));
		return -1;
	}

#if 0
	struct sockaddr_in servaddr;
	servaddr.sin_family = AF_INET;
	//servaddr.sin_port = htons(s_port);
	inet_aton(bind_addr, &servaddr.sin_addr);
	ret = bind(sock, &servaddr, sizeof(servaddr));
	if(ret < 0)
	{
		printf("[%d]%s\n", errno, strerror(errno));
		return ret;
	}
#endif

	return sock;
}

//
//int get_interface()
//{
//	struct ifaddrs *ifaddr, *ifa;
//	int family, s;
//	char host[NI_MAXHOST];
//
//	if (getifaddrs(&ifaddr) == -1) {
//	   perror("getifaddrs");
//	   exit(EXIT_FAILURE);
//	}
//
//	/* Walk through linked list, maintaining head pointer so we
//	  can free list later */
//
//	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
//	   family = ifa->ifa_addr->sa_family;
//
//	   /* Display interface name and family (including symbolic
//		  form of the latter for the common families) */
//
//	   printf("%s  address family: %d%s\n",
//			   ifa->ifa_name, family,
//			   (family == AF_PACKET) ? " (AF_PACKET)" :
//			   (family == AF_INET) ?   " (AF_INET)" :
//			   (family == AF_INET6) ?  " (AF_INET6)" : "");
//
//	   /* For an AF_INET* interface address, display the address */
//
//	   if (family == AF_INET || family == AF_INET6) {
//		   s = getnameinfo(ifa->ifa_addr,
//				   (family == AF_INET) ? sizeof(struct sockaddr_in) :
//										 sizeof(struct sockaddr_in6),
//				   host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
//		   if (s != 0) {
//			   printf("getnameinfo() failed: %s\n", gai_strerror(s));
//			   exit(EXIT_FAILURE);
//		   }
//		   printf("\taddress: <%s>\n", host);
//	   }
//	}
//
//	freeifaddrs(ifaddr);
//	exit(EXIT_SUCCESS);
//}



int main(int argc, char ** argv)
{
	int ret = get_interface();
	printf("getifaddrs ret=[%d]\n", ret);
	//return 0;

	if(argc < 4)
	{
		printf("usage:application dev dst_ip dst_port\n");
		abort();
	}


	int sock1 = create_tcp_sock(argv[1], "", 11111);
	printf("sock1 = [%d]\n", sock1);
	//int sock2 = create_tcp_sock(argv[3], "", 22222);
	//printf("sock2 = [%d]\n", sock2);

	connect_server(sock1, argv[2], atoi(argv[3]));
	//connect_server(sock2, "10.1.1.246", 22);
	return 0;
}



